package site.teamo.biu.net.common.util;

import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.IOException;

/**
 * @author haocongshun
 * @date 2023/03/31 15:53:42
 */
@Slf4j
public class Ip2RegionSearcher {

    private final Searcher searcher;

    private Ip2RegionSearcher(Searcher searcher) {
        this.searcher = searcher;
    }

    public static Ip2RegionSearcher create(String path) throws IOException {
        // 1、从 dbPath 加载整个 xdb 到内存。
        byte[] cBuff = Searcher.loadContentFromFile(path);
        // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
        return new Ip2RegionSearcher(Searcher.newWithBuffer(cBuff));
    }

    public String search(String ip) throws Exception {
        return searcher.search(ip);
    }

    public void close() throws IOException {
        searcher.close();
    }
}
